package com.jinyang.jetpackdemo.util.event

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.jinyang.jetpackdemo.util.event.LiveDataUtils.setValue
import com.jinyang.jetpackdemo.util.event.LiveEventObserver.Companion.bind

/**
 * @Author: LiuJinYang
 * @CreateDate: 2021/11/24
 * @Description:
 */
class EventMutableLiveData<T> : MutableLiveData<T>() {
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        bind(this, owner, observer)
    }

    override fun postValue(value: T) {
        setValue(this, value)
    }
}

/**
 * 用作事件总线的 [MediatorLiveData]
 *
 * @see AsEventBus
 *
 *
 * @author funnywolf
 * @since 2019-05-18
 */
internal class EventMediatorLiveData<T> : MediatorLiveData<T>() {
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        bind(this, owner, observer)
    }

    override fun postValue(value: T) {
        setValue(this, value)
    }
}

/**
 * 该注解只用于 [androidx.lifecycle.LiveData]，用于表示 LiveData 是当成事件总线用的，需要注意：
 * - 观察者在非激活状态（onStart 之后，onPause 之前）时不会产生回调，会丢失事件
 * - postValue 可能会被覆盖，只能用 setValue 来更新值
 * - LiveData 的事件都是黏性的，不使用时手动抛出一个 null 事件，以防下次绑定时会发送存在之前的旧数据；
 *
 * @see LiveDataUtils
 *
 * @see LiveEventObserver
 *
 * @see EventMutableLiveData
 *
 * @see EventMediatorLiveData
 *
 *
 * @author funnywolf
 * @since 2019-05-06
 */
@Target(AnnotationTarget.FIELD)
internal annotation class AsEventBus 